package com.itcm.skymail.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itcm.common.utils.PageUtils;
import com.itcm.common.utils.Query;
import com.itcm.skymail.member.dao.MemberDao;
import com.itcm.skymail.member.entity.MemberEntity;
import com.itcm.skymail.member.exception.PhoneExistException;
import com.itcm.skymail.member.exception.UsernameExistException;
import com.itcm.skymail.member.service.MemberService;
import com.itcm.skymail.member.vo.LoginUser;
import com.itcm.skymail.member.vo.RegistMember;
import com.itcm.skymail.member.vo.WeiboAccessVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;


@Service("memberService")
@Slf4j
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(RegistMember user) {
        // todo 默认等级 - memberLevel
        checkUsernameExist(user.getUsername());
        checkPhoneExist(user.getPhone());
        MemberEntity memberEntity = new MemberEntity();
        memberEntity.setUsername(user.getUsername());
        memberEntity.setMobile(user.getPhone());
        // 加密
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(user.getPassword());
        memberEntity.setPassword(encode);
        this.baseMapper.insert(memberEntity);
    }

    @Override
    public void checkUsernameExist(String username) throws UsernameExistException {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (count > 0) {
            throw new UsernameExistException();
        }
    }

    @Override
    public void checkPhoneExist(String phone) throws PhoneExistException {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (count > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public MemberEntity login(LoginUser user) {
        String account = user.getAccount();
        String password = user.getPassword();

        MemberEntity entity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", account).or().eq("mobile", account));
        if (entity == null) {
            // 用户名不存在
            return null;
        } else {
            String passwordDb = entity.getPassword();
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            boolean matches = encoder.matches(password, passwordDb);
            if (matches) {
                entity.setPassword(null);
                return entity;
            } else {
                // 密码错误
                return null;
            }
        }
    }

    /*
     *  社交登录-微博
     */
    @Override
    public MemberEntity weiboLogin(WeiboAccessVo vo) {
        String uid = vo.getUid();
        MemberEntity entity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("weibo_uid", uid));
        if (entity == null) {
            log.info("该微博第一次登录本网站，进行自动注册");
            // 不存在，自动注册
            MemberEntity regist = new MemberEntity();
            // todo 默认等级 - memberLevel
            // 使用accessToken 去请求微博 获取用户信息
            try {
                Map<String, String> map = new HashMap<>();
                map.put("access_token", vo.getAccessToken());
                map.put("uid", vo.getUid());
                log.info("access_token is {}, uid is {}", vo.getAccessToken(), vo.getUid());
                ResponseEntity<String> response = restTemplate.getForEntity("https://api.weibo.com/2/users/show.json?access_token={access_token}&uid={uid}", String.class, map);
                if (response.getStatusCode().is2xxSuccessful()) {
                    System.out.println(response.getBody());
                    JSONObject jsonObject = JSON.parseObject(response.getBody());
                    String name = jsonObject.getString("name");
                    log.info("获取微博数据成功，昵称：{}", name);
                    String gender = jsonObject.getString("gender");
                    regist.setNickname(name);
                    regist.setGender("m".equals(gender) ? 1 : 0);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            regist.setWeiboUid(vo.getUid());
            regist.setWeiboAccessToken(vo.getAccessToken());
            regist.setWeiboExpiresIn(vo.getExpiresIn());
            this.baseMapper.insert(regist);
            return regist;
        } else {
            log.info("该微博已是本网站会员，登录成功");
            // 已存在，返回帐户信息
            MemberEntity updateMember = new MemberEntity();
            updateMember.setId(entity.getId());
            updateMember.setWeiboAccessToken(vo.getAccessToken());
            updateMember.setWeiboExpiresIn(vo.getExpiresIn());
            // 更新
            this.baseMapper.updateById(updateMember);
            entity.setWeiboExpiresIn(vo.getExpiresIn());
            entity.setWeiboAccessToken(vo.getAccessToken());
            return entity;
        }
    }
}